package org.to_zero.ssm.sdm.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.to_zero.ssm.sdm.entity.vo.ResponseEntity;
import org.to_zero.ssm.sdm.service.FileTransferService;
import org.to_zero.ssm.sdm.util.SysUtil;
import org.to_zero.ssm.sdm.util.Toolkit;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class FileTransferServiceImpl implements FileTransferService {
    @Override
    public ResponseEntity upload(MultipartFile[] files) {
        List<String> succeedUploadPath = new ArrayList<>();
        for (MultipartFile file : files) {
            if (Objects.nonNull(file)) {
                String filename = file.getOriginalFilename();
                filename = Objects.requireNonNull(filename).substring(filename.lastIndexOf("."));
                filename = Toolkit.getUUIDToken().concat(filename);
                File path = new File(SysUtil.getUploadPath());
                if (path.exists() || path.mkdirs()) {
                    try {
                        file.transferTo(new File(path, filename));
                        succeedUploadPath.add(SysUtil.IMG_PATH.concat(filename));
                    } catch (IOException e) {
                        e.printStackTrace();
                        return ResponseEntity.error("文件上传失败");
                    }
                }
            }
        }
        return ResponseEntity.success(succeedUploadPath);
    }

    @Override
    public ResponseEntity download(String fileName, HttpSession session) {
        return ResponseEntity.error();
    }
}
